import { Middleware, MiddlewareContext } from '../../core/types';

export interface LogRequest {
  method?: string;
  url?: string;
  headers?: Record<string, string>;
  data?: any;
}

export interface LogResponse {
  status?: number;
  url?: string;
  data?: any;
  error?: any;
}

export interface LoggerOptions {
  level?: string;
  log?: (...args: any[]) => void;
  requestLogger?: (req: LogRequest) => void;
  responseLogger?: (res: LogResponse) => void;
}

export function logger(options: LoggerOptions = {}): Middleware {
  const {
    level = 'info',
    log = console.log,
    requestLogger = (req) => log(`[Request] ${req.method} ${req.url}`),
    responseLogger = (res) => log(`[Response] ${res.status} ${res.url}`),
  } = options;

  return async (ctx: MiddlewareContext, next) => {
    requestLogger({
      method: ctx.config.method,
      url: ctx.config.url,
      headers: ctx.config.headers,
      data: ctx.config.data,
    });

    await next();

    responseLogger({
      status: ctx.response?.status,
      url: ctx.config.url,
      data: ctx.response?.data,
      error: ctx.error,
    });
  };
}
